<template>
  <div class="app-container">
    <div class="form-container">
      <!-- 基础信息区 -->
      <el-tabs type="border-card">
        <el-tab-pane>
          <span slot="label"><i class="el-icon-date"></i> 基础信息</span>
          <el-form ref="form" :model="form" :rules="rules" label-width="100px">
            <el-row :gutter="20">
              <el-col :span="isEdit ? 12 : 8">
                <el-form-item label="计划编号" prop="planCode" required>
                  <el-input v-model="form.planCode" placeholder="请输入" :disabled="isSystemCode || isEdit"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="4" v-if="!isEdit">
                <el-switch
                  v-model="isSystemCode"
                  active-text="系统编号"
                  inactive-text=""
                  style="margin-top: 13px;"
                  @change="handleSystemCodeChange"
                ></el-switch>
              </el-col>
              <el-col :span="12">
                <el-form-item label="计划名称" prop="planName" required>
                  <el-input v-model="form.planName" placeholder="请输入"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="来源类型" prop="sourceType" required>
                  <el-select v-model="form.sourceType" placeholder="生产订单" style="width: 100%">
                    <el-option
                      v-for="item in sourceTypeOptions"
                      :key="item.dictValue"
                      :label="item.dictLabel"
                      :value="item.dictValue"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="订单编号" prop="orderCode">
                  <el-input v-model="form.orderCode" placeholder="请输入" :disabled="isEdit"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="成品名称" prop="productName">
                  <el-input
                    placeholder="请选择成品"
                    v-model="form.productName"
                    class="input-with-select"
                  >
                    <el-button slot="append" icon="el-icon-search" @click="openProductSelection"></el-button>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="成品编号" prop="productCode">
                  <el-input v-model="form.productCode" placeholder="请输入" disabled></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="规格型号" prop="specification">
                  <el-input v-model="form.specification" placeholder="请输入" disabled></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="成品类型" prop="productType">
                  <dict-tag :options="dict.type.product_type" :value="form.productType" />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="单位" prop="unit">
                  <el-input v-model="form.unit" placeholder="请输入" disabled></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="计划数量" prop="plannedQty" required>
                  <el-input-number v-model="form.plannedQty" :min="1" controls-position="right" style="width: 100%"></el-input-number>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="开工时间" prop="planStartTime">
                  <el-date-picker
                    v-model="form.planStartTime"
                    type="date"
                    placeholder="请选择日期"
                    style="width: 100%"
                    value-format="yyyy-MM-dd"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="完工时间" prop="planEndTime">
                  <el-date-picker
                    v-model="form.planEndTime"
                    type="date"
                    placeholder="请选择日期"
                    style="width: 100%"
                    value-format="yyyy-MM-dd"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="需求日期" prop="requiredDate">
                  <el-date-picker
                    v-model="form.requiredDate"
                    type="date"
                    placeholder="请选择日期"
                    style="width: 100%"
                    value-format="yyyy-MM-dd"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input
                    type="textarea"
                    v-model="form.remark"
                    placeholder="请输入"
                    :rows="4"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="附件" prop="attachment">
                  <div class="upload-container" @click="triggerUpload">
                    <el-upload
                      ref="upload"
                      class="upload-hidden"
                      action="#"
                      :http-request="uploadFile"
                      :file-list="fileList"
                      :before-upload="beforeUpload"
                      :on-remove="handleRemove"
                      multiple
                      drag
                    >
                      <div class="upload-area">
                        <i class="el-icon-upload"></i>
                        <div class="upload-text">点击或者拖动文件到虚线框内上传</div>
                        <div class="upload-hint">支持 docx, xls, PDF, rar, zip, PNG, JPG 等类型的文件</div>
                      </div>
                    </el-upload>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-divider>
              <span class="bom-title">BOM组成</span>
            </el-divider>
            
            <el-row>
              <el-col :span="24">
                <div class="bom-container">
                  <div class="folder-icon" v-if="!selectedBom">
                    <svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" viewBox="0 0 24 24" fill="#DCDFE6">
                      <path d="M10 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/>
                    </svg>
                  </div>
                  <div class="bom-text" v-if="!selectedBom">暂无数据</div>
                  <div class="bom-info" v-else>
                    <div class="bom-header">
                      <div class="bom-title-info">
                        <span>BOM编号：{{ selectedBom.bom_code }}</span>
                        <span>版本号：{{ selectedBom.bom_version }}</span>
                      </div>
                      <el-button type="text" icon="el-icon-delete" @click="clearSelectedBom">清除</el-button>
                    </div>
                    <el-table
                      :data="bomDetailList"
                      border
                      size="small"
                      style="width: 100%"
                      class="bom-detail-table"
                    >
                      <el-table-column label="序号" type="index" width="50" align="center"></el-table-column>
                      <el-table-column prop="material_code" label="物料编码" min-width="120" align="center"></el-table-column>
                      <el-table-column prop="material_name" label="物料名称" min-width="150" align="center"></el-table-column>
                      <el-table-column prop="specification" label="规格型号" min-width="100" align="center"></el-table-column>
                      <el-table-column prop="unit" label="单位" width="60" align="center"></el-table-column>
                      <el-table-column prop="quantity" label="用量" width="80" align="center"></el-table-column>
                      <el-table-column prop="remark" label="备注" min-width="120" align="center"></el-table-column>
                    </el-table>
                  </div>
                  <div class="bom-action">
                    <el-tooltip :disabled="form.productId" content="请先选择成品!" placement="right" effect="light">
                      <el-button type="primary" class="select-bom-button" @click="selectBom">选择BOM</el-button>
                    </el-tooltip>
                  </div>
                </div>
              </el-col>
            </el-row>
            
            <el-row>
              <el-col :span="24" style="text-align: center; margin-top: 20px;">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
    
    <!-- 产品选择对话框 -->
    <el-dialog title="选择成品" :visible.sync="productDialogVisible" width="40%" append-to-body>
      <el-form :model="productQuery" ref="productQueryForm" :inline="true" class="demo-form-inline" size="small">
        <el-form-item>
          <el-input v-model="productQuery.keyword" placeholder="请输入产品编号/名称" clearable style="width: 180px;"></el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="productQuery.unit" placeholder="请选择单位" clearable style="width: 120px;">
            <el-option label="个" value="个"></el-option>
            <el-option label="件" value="件"></el-option>
            <el-option label="台" value="台"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="productQuery.type" placeholder="请选择类型" clearable style="width: 120px;">
            <el-option label="成品" value="成品"></el-option>
            <el-option label="半成品" value="半成品"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="productQuery.property" placeholder="请选择产品属性" clearable style="width: 120px;">
            <el-option label="自制" value="自制"></el-option>
            <el-option label="外购" value="外购"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="searchProducts">查询</el-button>
          <el-button icon="el-icon-refresh" size="small" @click="resetProductQuery">重置</el-button>
        </el-form-item>
      </el-form>
      
      <el-table
        v-loading="productLoading"
        :data="productList"
        border
        size="small"
        style="width: 100%"
        @selection-change="handleProductSelectionChange"
        height="300"
      >
        <el-table-column type="selection" width="40" align="center"></el-table-column>
        <el-table-column label="序号" type="index" width="40" align="center"></el-table-column>
        <el-table-column prop="product_code" label="产品编号" width="90" align="center"></el-table-column>
        <el-table-column prop="product_name" label="产品名称" min-width="120" align="center"></el-table-column>
        <el-table-column prop="product_sfn" label="规格型号" min-width="90" align="center">
          <template slot-scope="scope">
            <span :style="{color: '#1890ff'}">{{ scope.row.product_sfn }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="product_unit" label="单位" width="60" align="center"></el-table-column>
        <el-table-column prop="product_type" label="产品类型" width="70" align="center" :formatter="formatProductType"></el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <span class="total-text">共 {{ productTotal }} 条</span>
        <div class="pagination-wrapper">
          <span class="page-size">
            <el-select v-model="productQuery.pageSize" size="mini" @change="handleProductSizeChange" style="width: 80px;">
              <el-option
                v-for="item in [10, 20, 30, 50]"
                :key="item"
                :label="`${item}条/页`"
                :value="item">
              </el-option>
            </el-select>
          </span>
          <el-pagination
            small
            background
            @current-change="handleProductCurrentChange"
            :current-page="productQuery.pageNum"
            :page-size="productQuery.pageSize"
            layout="prev, pager, next, jumper"
            :pager-count="5"
            :total="productTotal">
          </el-pagination>
        </div>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="productDialogVisible = false">取消</el-button>
        <el-button type="primary" size="small" @click="confirmProductSelect">确定</el-button>
      </div>
    </el-dialog>
    
    <!-- BOM选择对话框 -->
    <el-dialog title="选择BOM" :visible.sync="bomDialogVisible" width="40%" append-to-body>
      <div class="bom-dialog-header">
        <div class="product-info">
          <span>产品名称：{{ form.productName }}</span>
          <span>产品编号：{{ form.productCode }}</span>
          <span>规格型号：{{ form.specification }}</span>
          <span>单位：{{ form.unit }}</span>
        </div>
      </div>
      
      <el-table
        v-loading="bomLoading"
        :data="bomList"
        border
        style="width: 100%"
        @row-click="handleBomSelect"
        highlight-current-row
        size="small"
        height="300"
      >
        <el-table-column type="selection" width="55" align="center">
          <template slot-scope="scope">
            <el-radio v-model="selectedBomId" :label="scope.row.bom_id" @change="handleBomSelect(scope.row)">&nbsp;</el-radio>
          </template>
        </el-table-column>
        <el-table-column label="序号" type="index" width="55" align="center"></el-table-column>
        <el-table-column prop="bom_code" label="BOM编号" min-width="150" align="center"></el-table-column>
        <el-table-column prop="bom_version" label="版本号" width="100" align="center"></el-table-column>
        <el-table-column prop="bom_status" label="默认BOM" width="100" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.bom_status === '1' ? '是' : '否' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="bom_output" label="日产量" width="100" align="center"></el-table-column>
      </el-table>
      
      <pagination
        v-show="bomTotal > 0"
        :total="bomTotal"
        :page.sync="bomQuery.pageNum"
        :limit.sync="bomQuery.pageSize"
        @pagination="getBomList"
      />
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="bomDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmBomSelect">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getProductionPlan, updateProductionPlan, addProductionPlan } from "@/api/sc/productionPlan";
import { listProducts, listBomsByProductId, findBomDetails } from "@/api/basic/product";
import { getAutoNumbers, getAutoNumbersConsume } from "@/api/basic/numbers";
import Pagination from "@/components/Pagination";
import DictTag from "@/components/DictTag";

export default {
  name: "EditPlan",
  dicts: ['product_type'],
  components: {
    Pagination,
    DictTag
  },
  data() {
    return {
      // 页面标题
      title: "修改生产计划",
      // 是否为修改模式
      isEdit: true,
      // 表单数据
      form: {
        planCode: "",
        planName: "",
        sourceType: "生产订单",
        orderCode: "",
        productId: undefined,
        productName: "",
        productCode: "",
        specification: "",
        productType: "",
        unit: "",
        plannedQty: 1,
        planStartTime: "",
        planEndTime: "",
        requiredDate: "",
        remark: "",
        orderQty: 0  // 添加订单数量字段
      },
      // 是否使用系统编号
      isSystemCode: true,
      // 表单验证规则
      rules: {
        planName: [
          { required: true, message: "计划名称不能为空", trigger: "blur" },
          { max: 50, message: "长度不能超过50个字符", trigger: "blur" }
        ],
        sourceType: [
          { required: true, message: "来源类型不能为空", trigger: "change" }
        ],
        productName: [
          { required: true, message: "请选择产品", trigger: "change" }
        ],
        plannedQty: [
          { required: true, message: "计划数量不能为空", trigger: "blur" },
          { validator: this.validatePlannedQty, trigger: "blur" }
        ],
        planStartTime: [
          { validator: this.validateStartTime, trigger: "change" }
        ],
        planEndTime: [
          { validator: this.validateEndTime, trigger: "change" }
        ],
        requiredDate: [
          { validator: this.validateRequiredDate, trigger: "change" }
        ]
      },
      // 产品下拉选项
      productOptions: [],
      // 产品加载状态
      productLoading: false,
      // 来源类型选项
      sourceTypeOptions: [
        { dictLabel: "生产订单", dictValue: "生产订单" }
      ],
      // 上传文件列表
      fileList: [],
      
      // 产品选择对话框
      productDialogVisible: false,
      productQuery: {
        pageNum: 1,
        pageSize: 10,
        keyword: "",
        unit: "",
        type: "",
        property: ""
      },
      productList: [],
      productTotal: 0,
      selectedProduct: null,
      
      // BOM选择对话框
      bomDialogVisible: false,
      bomQuery: {
        pageNum: 1,
        pageSize: 10,
        productId: undefined
      },
      bomList: [],
      bomTotal: 0,
      bomLoading: false,
      selectedBom: null,
      selectedBomId: null,
      bomDetailList: [],
    };
  },
  created() {
    const planCode = this.$route.query.planCode;
    if (planCode) {
      this.isEdit = true;
      this.title = "修改生产计划";
      this.getPlanData(planCode);
    } else {
      this.isEdit = false;
      this.title = "新增生产计划";
      this.generatePlanCode();
    }
  },
  watch: {
    // 监听路由变化，页面重新加载时刷新数据
    '$route'(to) {
      if (to.path === '/sc/plan/edit' || to.name === 'EditPlan') {
        console.log('编辑计划页面路由变化，刷新数据');
        const planCode = to.query.planCode;
        if (planCode) {
          this.isEdit = true;
          this.title = "修改生产计划";
          this.getPlanData(planCode);
        } else {
          this.isEdit = false;
          this.title = "新增生产计划";
          this.generatePlanCode();
        }
      }
    }
  },
  methods: {
    // 获取计划数据
    getPlanData(planCode) {
      getProductionPlan(planCode).then(response => {
        this.form = response.data;

        // 如果是生产订单来源，获取订单数量信息
        if (this.form.sourceType === 'PRODUCTION_ORDER' && this.form.productionOrderId) {
          this.getOrderQtyInfo(this.form.productionOrderId, this.form.productId);
        }

        // 如果有关联的产品，则自动加载其BOM信息
        if (this.form.productId) {
          this.loadAssociatedBom();
        }
      });
    },

    // 获取订单数量信息
    getOrderQtyInfo(productionOrderId, productId) {
      import("@/api/sc/productionOrder").then(api => {
        api.getProductionOrderDetails(productionOrderId).then(response => {
          if (response.code === 200 && response.data && response.data.products) {
            const product = response.data.products.find(p => p.productId === productId);
            if (product) {
              this.form.orderQty = product.qtyNum || 0;
            }
          }
        }).catch(() => {
          console.error('获取订单数量信息失败');
        });
      });
    },

    // 加载关联的BOM
    loadAssociatedBom() {
      listBomsByProductId(this.form.productId).then(response => {
        if (response.code === 200 && response.rows && response.rows.length > 0) {
          // 查找默认的BOM (status '1')
          const activeBom = response.rows.find(b => b.bom_status === '1');
          if (activeBom) {
            this.selectedBom = activeBom;
            this.getBomDetail(); // 加载BOM详情
          }
        }
      });
    },

    // 生成计划编号
    generatePlanCode() {
      getAutoNumbers(6).then(response => {
        if (response.code === 200) {
          this.form.planCode = response.msg;
        } else {
          this.$message.error('获取计划编号失败');
        }
      }).catch(() => {
        this.$message.error('获取计划编号失败');
      });
    },
    
    // 处理系统编号开关变化
    handleSystemCodeChange(val) {
      if (val) {
        // 如果开启系统编号，则生成编号
        this.generatePlanCode();
      } else {
        // 如果关闭系统编号，则清空编号
        this.form.planCode = '';
      }
    },
    
    // 触发上传
    triggerUpload() {
      this.$refs.upload.$el.click();
    },
    
    // 打开产品选择弹窗
    openProductSelection() {
      // 修改模式下不允许更换产品
      if (this.isEdit) {
        this.$message.warning("修改模式下不允许更换产品。");
        return;
      }
      this.productDialogVisible = true;
      this.getProductList();
    },
    
    // 获取产品列表
    getProductList() {
      this.productLoading = true;
      listProducts({
        pageNum: this.productQuery.pageNum,
        pageSize: this.productQuery.pageSize,
        keyword: this.productQuery.keyword,
        productUnit: this.productQuery.unit,
        productType: this.productQuery.type,
        productProperty: this.productQuery.property
      }).then(response => {
        this.productLoading = false;
        if (response.code === 200) {
          this.productList = response.rows;
          this.productTotal = response.total;
        }
      }).catch(() => {
        this.productLoading = false;
        // 模拟数据
        this.productList = [
          { product_id: 1, product_code: 'CP025', product_name: '产品一', product_sfn: '蓝色', product_type: '成品', product_unit: '个', product_property: '自制' },
          { product_id: 2, product_code: 'CP025', product_name: '产品一', product_sfn: '蓝色', product_type: '成品', product_unit: '个', product_property: '自制' },
          { product_id: 3, product_code: 'CP025', product_name: '产品一', product_sfn: '蓝色', product_type: '成品', product_unit: '个', product_property: '自制' },
          { product_id: 4, product_code: 'CP025', product_name: '产品一', product_sfn: '蓝色', product_type: '成品', product_unit: '个', product_property: '自制' },
          { product_id: 5, product_code: 'CP025', product_name: '产品一', product_sfn: '蓝色', product_type: '成品', product_unit: '个', product_property: '自制' }
        ];
        this.productTotal = 50;
      });
    },
    
    // 搜索产品
    searchProducts() {
      this.productQuery.pageNum = 1;
      this.getProductList();
    },
    
    // 重置产品查询条件
    resetProductQuery() {
      this.productQuery = {
        pageNum: 1,
        pageSize: 10,
        keyword: "",
        unit: "",
        type: "",
        property: ""
      };
      this.getProductList();
    },
    
    // 处理产品表格选择变化
    handleProductSelectionChange(selection) {
      if (selection.length > 0) {
        this.selectedProduct = selection[0];
      } else {
        this.selectedProduct = null;
      }
    },
    
    // 处理产品页码变化
    handleProductCurrentChange(currentPage) {
      this.productQuery.pageNum = currentPage;
      this.getProductList();
    },
    
    // 处理产品每页条数变化
    handleProductSizeChange(size) {
      this.productQuery.pageSize = size;
      this.productQuery.pageNum = 1;
      this.getProductList();
    },
    
    // 确认产品选择
    confirmProductSelect() {
      if (this.selectedProduct) {
        this.form.productId = this.selectedProduct.product_id;
        this.form.productName = this.selectedProduct.product_name;
        this.form.productCode = this.selectedProduct.product_code;
        this.form.specification = this.selectedProduct.product_sfn;
        this.form.productType = this.formatProductType(this.selectedProduct);
        this.form.unit = this.selectedProduct.product_unit;
        this.productDialogVisible = false;
        
        // 清空已选BOM
        this.selectedBom = null;
        this.selectedBomId = null;
      } else {
        this.$message.warning('请选择一个产品！');
      }
    },
    
    // 格式化产品类型
    formatProductType(row, column) {
      const type = row.product_type;
      const option = this.dict.type.product_type.find(item => item.dictValue == type);
      return option ? option.dictLabel : type;
    },
    
    // 选择BOM
    selectBom() {
      if (!this.form.productId) {
        this.$message.warning('请先选择成品！');
        return;
      }
      this.bomDialogVisible = true;
      this.getBomList();
    },
    
    // 获取BOM列表
    getBomList() {
      this.bomLoading = true;
      listBomsByProductId(this.form.productId).then(response => {
        this.bomLoading = false;
        if (response.code === 200) {
          this.bomList = response.rows;
          this.bomTotal = response.total;
          if (!this.bomList || this.bomList.length === 0) {
            this.$message.info("未找到该产品的BOM信息");
          } else {
            // 如果有默认BOM，则自动选中
            const defaultBom = this.bomList.find(b => b.bom_status === '1');
            if (defaultBom) {
              this.handleBomSelect(defaultBom);
            }
          }
        } else {
          this.bomList = [];
          this.bomTotal = 0;
        }
      }).catch(() => {
        this.bomLoading = false;
        this.$message.error('获取BOM列表失败');
      });
    },
    
    // 处理BOM行选择
    handleBomSelect(row) {
      this.selectedBom = row;
      this.selectedBomId = row.bom_id;
    },
    
    // 确认BOM选择
    confirmBomSelect() {
      if (this.selectedBom) {
        this.bomDialogVisible = false;
        // 获取BOM详情
        this.getBomDetail();
      } else {
        this.$message.warning('请选择一个BOM！');
      }
    },
    
    // 获取BOM详情
    getBomDetail() {
      findBomDetails(this.selectedBom.bom_id).then(response => {
        console.log("成功获取BOM详情响应:", response);
        if (response && response.code === 200) {
          this.bomDetailList = response.rows;
        } else {
          this.bomDetailList = [];
          this.$message.error("获取BOM详情失败: " + (response ? response.msg : '无响应'));
        }
      }).catch(error => {
        console.error("获取BOM详情接口调用失败:", error);
        this.$message.error("获取BOM详情接口调用失败");
        this.bomDetailList = [];
      });
    },
    
    // 清除已选BOM
    clearSelectedBom() {
      this.selectedBom = null;
      this.selectedBomId = null;
      this.bomDetailList = [];
    },
    
    // 上传前检查文件类型和大小
    beforeUpload(file) {
      const isValidType = /\.(doc|docx|xls|xlsx|pdf|rar|zip|png|jpg|jpeg)$/i.test(file.name);
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isValidType) {
        this.$message.error('上传文件格式不支持!');
        return false;
      }
      if (!isLt10M) {
        this.$message.error('上传文件大小不能超过 10MB!');
        return false;
      }
      return true;
    },
    
    // 上传文件处理
    uploadFile(options) {
      // 这里应该调用实际的文件上传API
      console.log('文件上传:', options.file);
      // 假设上传成功
      this.fileList.push({
        name: options.file.name,
        url: URL.createObjectURL(options.file)
      });
      options.onSuccess();
    },
    
    // 移除文件
    handleRemove(file) {
      const index = this.fileList.indexOf(file);
      if (index !== -1) {
        this.fileList.splice(index, 1);
      }
    },
    
    // 表单提交
    async submitForm() {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          // 额外的日期逻辑验证
          if (!this.validateDateLogic()) {
            return;
          }

          // 如果开启了自动编号且不是编辑模式，在提交前获取真正的编号
          if (!this.isEdit && this.isSystemCode && this.form.planCode) {
            try {
              const response = await getAutoNumbersConsume(6);
              if (response.code === 200) {
                this.form.planCode = response.msg;
              }
            } catch (error) {
              this.$message.error('获取最终编号失败');
              return;
            }
          }

          // 根据isEdit标志决定调用哪个API
          const apiCall = this.isEdit ? updateProductionPlan : addProductionPlan;

          apiCall(this.form).then(response => {
            if (response.code === 200) {
              this.$modal.msgSuccess(this.isEdit ? "修改成功" : "新增成功");
              this.cancel();
            } else {
              this.$modal.msgError(response.msg || (this.isEdit ? "修改失败" : "新增失败"));
            }
          }).catch(() => {
            this.$modal.msgError("操作失败，请稍后重试");
          });
        }
      });
    },
    
    // 取消按钮
    cancel() {
      this.$router.push({ path: "/sc/plan" });
    },

    // 验证开工时间
    validateStartTime(rule, value, callback) {
      if (!value) {
        callback();
        return;
      }

      const today = new Date();
      today.setHours(0, 0, 0, 0);
      const startDate = new Date(value);

      // 开工日期不能早于当前日期
      if (startDate < today) {
        callback(new Error('开工日期不能早于当前日期'));
        return;
      }

      // 如果完工时间已选择，开工时间不能晚于完工时间
      if (this.form.planEndTime) {
        const endDate = new Date(this.form.planEndTime);
        if (startDate > endDate) {
          callback(new Error('开工日期不能晚于完工日期'));
          return;
        }
      }

      callback();
    },

    // 验证完工时间
    validateEndTime(rule, value, callback) {
      if (!value) {
        callback();
        return;
      }

      const endDate = new Date(value);

      // 如果开工时间已选择，完工时间不能早于开工时间
      if (this.form.planStartTime) {
        const startDate = new Date(this.form.planStartTime);
        if (endDate < startDate) {
          callback(new Error('完工日期不能早于开工日期'));
          return;
        }
      }

      callback();
    },

    // 验证计划数量
    validatePlannedQty(rule, value, callback) {
      if (!value) {
        callback();
        return;
      }

      const plannedQty = Number(value);
      const orderQty = Number(this.form.orderQty);

      if (plannedQty <= 0) {
        callback(new Error('计划数量必须大于0'));
        return;
      }

      if (orderQty > 0 && plannedQty > orderQty) {
        callback(new Error(`计划数量不能大于订单数量(${orderQty})`));
        return;
      }

      callback();
    },

    // 验证需求日期
    validateRequiredDate(rule, value, callback) {
      if (!value) {
        callback();
        return;
      }

      const requiredDate = new Date(value);

      // 需求日期不能早于当前日期
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      if (requiredDate < today) {
        callback(new Error('需求日期不能早于当前日期'));
        return;
      }

      // 如果完工时间已选择，需求日期不能早于完工时间
      if (this.form.planEndTime) {
        const endDate = new Date(this.form.planEndTime);
        if (requiredDate < endDate) {
          callback(new Error('需求日期不能早于完工日期'));
          return;
        }
      }

      callback();
    },

    // 综合日期逻辑验证
    validateDateLogic() {
      const today = new Date();
      today.setHours(0, 0, 0, 0);

      // 检查开工日期
      if (this.form.planStartTime) {
        const startDate = new Date(this.form.planStartTime);
        if (startDate < today) {
          this.$modal.msgError("开工日期不能早于当前日期");
          return false;
        }
      }

      // 检查开工日期和完工日期的关系
      if (this.form.planStartTime && this.form.planEndTime) {
        const startDate = new Date(this.form.planStartTime);
        const endDate = new Date(this.form.planEndTime);
        if (startDate > endDate) {
          this.$modal.msgError("开工日期不能晚于完工日期");
          return false;
        }
      }

      // 检查需求日期
      if (this.form.requiredDate) {
        const requiredDate = new Date(this.form.requiredDate);
        if (requiredDate < today) {
          this.$modal.msgError("需求日期不能早于当前日期");
          return false;
        }

        // 需求日期不能早于完工日期
        if (this.form.planEndTime) {
          const endDate = new Date(this.form.planEndTime);
          if (requiredDate < endDate) {
            this.$modal.msgError("需求日期不能早于完工日期");
            return false;
          }
        }
      }

      return true;
    }
  }
};
</script>

<style scoped>
.form-container {
  background-color: #fff;
  padding: 10px;
}

.el-tabs--border-card {
  box-shadow: none;
}

.upload-container {
  width: 100%;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  text-align: center;
  padding: 20px 0;
  cursor: pointer;
}

.upload-container:hover {
  border-color: #409EFF;
}

.upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.upload-area .el-icon-upload {
  font-size: 48px;
  color: #c0c4cc;
  margin-bottom: 10px;
}

.upload-text {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}

.upload-hint {
  font-size: 12px;
  color: #909399;
}

.input-with-select .el-input-group__append {
  background-color: #fff;
}

.bom-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.bom-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin: 20px 0;
  padding: 30px 0;
}

.folder-icon {
  margin-bottom: 20px;
}

.bom-text {
  font-size: 14px;
  color: #909399;
  margin-bottom: 20px;
}

.warning-text {
  color: #E6A23C;
  font-size: 12px;
  margin-left: 10px;
}

.warning-text i {
  margin-right: 5px;
}

.upload-hidden {
  width: 100%;
  height: 100%;
}

.upload-hidden >>> .el-upload {
  width: 100%;
}

.upload-hidden >>> .el-upload-dragger {
  width: 100%;
  height: 100%;
  border: none;
  padding: 0;
  margin: 0;
}

.bom-dialog-header {
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.product-info {
  display: flex;
  flex-wrap: wrap;
}

.product-info span {
  margin-right: 20px;
  line-height: 30px;
}

.el-radio {
  margin-right: 0;
}

.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  font-size: 12px;
}

.pagination-wrapper {
  display: flex;
  align-items: center;
}

.page-size {
  margin-right: 10px;
}

.total-text {
  color: #606266;
  font-size: 12px;
}

.bom-info {
  width: 100%;
  margin-bottom: 20px;
}

.bom-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding: 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.bom-title-info {
  display: flex;
  flex-wrap: wrap;
}

.bom-title-info span {
  margin-right: 20px;
  font-weight: bold;
}

.bom-detail-table {
  margin-bottom: 15px;
}

.bom-action {
  display: flex;
  align-items: center;
}

.select-bom-button {
  margin-right: 10px;
}
</style>
